package org.feng.demofx.dao;

import org.feng.demofx.entity.Animal;
import org.feng.demofx.enums.AnimalTypeEnum;

import java.util.*;

/**
 * 模拟数据
 *
 * @author feng
 */
public class AnimalDataPool {
    private final static List<Animal> DATA = new ArrayList<>();
    private final static Map<Long, Animal> DATA_MAP = new HashMap<>();

    static {
        for (int i = 0; i < 30; i++) {
            Animal animal = new Animal();
            Long id = 1L + i;
            animal.setId(id);
            animal.setName("小明" + i);
            animal.setAge(10);
            DATA.add(animal);
            DATA_MAP.put(id, animal);
        }
    }

    public void insert(Animal animal) {
        animal.setId(newId());
        DATA.add(animal);
        DATA_MAP.put(animal.getId(), animal);
    }

    public List<Animal> listAll() {
        return DATA;
    }

    public List<Animal> listByParam(Long id, String name, AnimalTypeEnum animalType) {
        if(id != null) {
            return Collections.singletonList(DATA_MAP.get(id));
        }
        if(name == null || name.isEmpty()) {
            return listAll();
        }

        List<Animal> animals = new ArrayList<>();
        for (Animal animal : DATA) {
            if(name.equals(animal.getName())) {
                animals.add(animal);
            }

            if(animalType != null && animalType.equals(animal.getAnimalType())) {
                animals.add(animal);
            }
        }
        return animals;
    }

    public boolean deleteByIds(List<Long> ids) {
        for (Long id : ids) {
            Animal animal = DATA_MAP.get(id);
            DATA.remove(animal);
            DATA_MAP.remove(id);
        }
        return true;
    }

    public Long newId() {
        return DATA_MAP.keySet().stream().mapToLong(id -> id).max().orElse(0L) + 1;
    }
}
